import csv
import requests
import execjs
import json


class AirQualityCrawler:

    def __init__(self, url):
        self.url = url
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
        }
        self.data = {
            "hXhY1B2Kd": ""
        }
        self.ctx = None
        self.m4Sq1jVkq = "GETPROVINCEDATA"
        self.ogFjn1FgMP = {
            "type": "HOUR",
            "timepoint": "2024-03-02 05:00:00"
        }
        self.ciphertext = ""
        self.plaintext = ""
        self.json_data_list = {}
        self.field_name = [
            'place', 'aqi', 'pm2_5', 'pm10', 'so2', 'no2', 'co', 'o3', 'rank', 'pollutant', 'flag',
        ]

    def get_data(self):
        response = requests.post(url=self.url, headers=self.headers, data=self.data)
        self.ciphertext = response.text

    def parse_data(self):
        json_dict = json.loads(self.plaintext)
        self.json_data_list = json_dict['result']['data']['rows']

    def create_params(self):
        with open('request_params_encrypt.js', 'r', encoding='utf-8') as f:
            self.ctx = execjs.compile(f.read())
            self.data['hXhY1B2Kd'] = self.ctx.call("params_encryption", self.m4Sq1jVkq, self.ogFjn1FgMP)

    def data_decrypt(self):
        with open('response_data_decrypt.js', 'r', encoding='utf-8') as f:
            self.ctx = execjs.compile(f.read())
            self.plaintext = self.ctx.call("deIZLF7oahc0DLiXbqt", self.ciphertext)

    def save_data(self):
        with open('../data/data.csv', 'a', newline="", encoding="utf-8-sig") as f:
            csv_writer = csv.DictWriter(f, fieldnames=self.field_name)
            csv_writer.writerows(self.json_data_list)
            print("保存成功！")

    def run(self):
        with open('../data/data.csv', 'a', newline="", encoding="utf-8-sig") as f:
            csv_writer = csv.DictWriter(f, fieldnames=self.field_name)
            csv_writer.writeheader()

        self.create_params()
        self.get_data()
        self.data_decrypt()
        self.parse_data()
        self.save_data()


if __name__ == '__main__':
    main_url = "https://www.aqistudy.cn/apinew/aqistudyapi.php"
    spider = AirQualityCrawler(main_url)
    spider.run()
